// pages/settlements/settlements.js
const { apiService } = require('../../utils/api')
const { showSuccess, showError, formatPrice } = require('../../utils/util')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    settlements: [],
    loading: false,
    hasMore: true,
    pageNum: 1,
    pageSize: 10,
    totalAmount: 0, // 结算总金额
    summary: {
      totalCount: 0, // 总结算单数
      confirmedCount: 0, // 已确认数
      paidCount: 0, // 已支付数
      pendingAmount: 0 // 待支付金额
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadSettlements()
    this.loadSettlementSummary()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 页面显示时刷新数据
    this.refreshSettlements()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.refreshSettlements()
    this.loadSettlementSummary()
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.loadMoreSettlements()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '我的结算单',
      path: '/pages/settlements/settlements'
    }
  },

  /**
   * 加载结算单列表
   */
  async loadSettlements() {
    if (this.data.loading) return

    this.setData({ loading: true })

    try {
      const params = {
        pageNum: this.data.pageNum,
        pageSize: this.data.pageSize
      }

      const result = await apiService.getMySettlements(params)
      const newSettlements = result.list || []
      const settlements = this.data.pageNum === 1 ? newSettlements : [...this.data.settlements, ...newSettlements]

      this.setData({
        settlements: settlements,
        hasMore: newSettlements.length === this.data.pageSize,
        loading: false
      })
    } catch (error) {
      this.setData({ loading: false })
      showError(error.message || '加载结算单失败')
    }
  },

  /**
   * 加载结算统计信息
   */
  async loadSettlementSummary() {
    try {
      const total = await apiService.getMySettlementTotal()
      const settlements = this.data.settlements

      const summary = {
        totalCount: settlements.length,
        confirmedCount: settlements.filter(s => s.status === 2).length,
        paidCount: settlements.filter(s => s.status === 3).length,
        pendingAmount: settlements.filter(s => s.status === 2).reduce((sum, s) => sum + (s.totalAmount || 0), 0)
      }

      this.setData({
        totalAmount: total || 0,
        summary: summary
      })
    } catch (error) {
      console.error('加载结算统计失败:', error)
    }
  },

  /**
   * 刷新结算单列表
   */
  refreshSettlements() {
    this.setData({
      settlements: [],
      pageNum: 1,
      hasMore: true
    })
    this.loadSettlements()
  },

  /**
   * 加载更多结算单
   */
  loadMoreSettlements() {
    if (!this.data.hasMore || this.data.loading) return

    this.setData({
      pageNum: this.data.pageNum + 1
    })
    this.loadSettlements()
  },

  /**
   * 查看结算单详情
   */
  onSettlementTap(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/settlement-detail/settlement-detail?id=${id}`
    })
  },

  /**
   * 确认结算单
   */
  async onConfirmSettlement(e) {
    e.stopPropagation() // 阻止冒泡
    const id = e.currentTarget.dataset.id

    try {
      wx.showModal({
        title: '确认结算单',
        content: '确认后将进入支付流程，是否继续？',
        success: async (res) => {
          if (res.confirm) {
            await apiService.confirmSettlement(id)
            showSuccess('结算单确认成功')
            this.refreshSettlements()
            this.loadSettlementSummary()
          }
        }
      })
    } catch (error) {
      showError(error.message || '确认结算单失败')
    }
  },

  /**
   * 获取状态文本
   */
  getStatusText(status) {
    const statusMap = {
      1: '待确认',
      2: '已确认',
      3: '已支付'
    }
    return statusMap[status] || '未知状态'
  },

  /**
   * 获取状态样式类
   */
  getStatusClass(status) {
    const classMap = {
      1: 'status-pending',
      2: 'status-confirmed',
      3: 'status-paid'
    }
    return classMap[status] || ''
  }
})